<template>
  <div>
    <div v-if="loading" class="text-center mt-30">
      <a-spin></a-spin>
    </div>
    <div v-else>
      <div v-if="treeData.length > 0" class="playedu-old-tree">
        <div style="height: 40px" class="d-flex">
          <a-checkbox
            :checked="isAllChecked"
            @change="onChange"
          >
            全选
          </a-checkbox>
        </div>
        <a-tree
          v-if="type === 'single'"
          :tree-data="treeData"
          :selected-keys="selectKeys"
          :expanded-keys="expandKeys"
          :show-line="{ showLeafIcon }"
          @select="onSelect"
          @expand="onExpandSingle"
        >
          <template #title="{ name, count }">
            <span class="tree-title-elli">
              {{ props.showNum ? `${name}(${count || 0})` : name }}
            </span>
          </template>
        </a-tree>
        <a-tree
          v-else
          :tree-data="treeData"
          :checked-keys="checkKeys"
          :expanded-keys="expandKeys"
          :show-line="{ showLeafIcon }"
          selectable="false"
          checkable
          :check-strictly="true"
          multiple
          @check="onCheck"
          @expand="onExpand"
        >
          <template #title="{ name, count }">
            <span class="tree-title-elli">
              {{ props.showNum ? `${name}(${count || 0})` : name }}
            </span>
          </template>
        </a-tree>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import { Spin, Tree, Checkbox } from 'ant-design-vue'
import { department } from '../../api/index'

// 定义 props
const props = defineProps({
  type: {
    type: String,
    default: ''
  },
  refresh: {
    type: Boolean,
    default: false
  },
  showNum: {
    type: Boolean,
    default: false
  },
  selected: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update'])

// 响应式数据
const treeData = ref([])
const loading = ref(true)
const selectKeys = ref([])
const checkKeys = ref([])
const userTotal = ref(0)
const showLeafIcon = ref(true)
const expandKeys = ref([])
const totalKeys = ref([])

// 计算属性
const isAllChecked = computed(() => {
  if (props.type === 'single') {
    return selectKeys.value.length === totalKeys.value.length && totalKeys.value.length > 0
  } else {
    return checkKeys.value.toString() === totalKeys.value.toString()
  }
})

// 监听 selected 变化
watch(() => props.selected, (newVal) => {
  selectKeys.value = [...newVal]
  checkKeys.value = [...newVal]
})

// 监听 refresh 变化
watch(() => props.refresh, () => {
  loadDepartmentData()
})

// 生命周期
onMounted(() => {
  loadDepartmentData()
})

// 方法
const loadDepartmentData = async () => {
  loading.value = true
  try {
    const res = await department.departmentList({})
    const departments = res.data.departments
    const departCount = res.data.dep_user_count
    userTotal.value = res.data.user_total
    
    if (JSON.stringify(departments) !== '{}') {
      if (props.showNum) {
        const new_arr = checkNewArr(departments, 0, departCount)
        treeData.value = new_arr
        totalKeys.value = new_arr.map(node => node.key)
      } else {
        const new_arr = checkArr(departments, 0)
        treeData.value = new_arr
        totalKeys.value = new_arr.map(node => node.key)
      }
    } else {
      treeData.value = []
      totalKeys.value = []
    }
  } catch (error) {
    console.error('Failed to load department data:', error)
    treeData.value = []
    totalKeys.value = []
  } finally {
    loading.value = false
  }
}

const checkNewArr = (departments, id, counts) => {
  const arr = []
  if (!departments[id]) return arr
  
  for (let i = 0; i < departments[id].length; i++) {
    const item = departments[id][i]
    if (!departments[item.id]) {
      arr.push({
        name: item.name,
        count: counts ? counts[item.id] || 0 : 0,
        key: item.id
      })
    } else {
      const new_arr = checkNewArr(departments, item.id, counts)
      arr.push({
        name: item.name,
        count: counts ? counts[item.id] || 0 : 0,
        key: item.id,
        children: new_arr
      })
    }
  }
  return arr
}

const checkArr = (departments, id) => {
  const arr = []
  if (!departments[id]) return arr
  
  for (let i = 0; i < departments[id].length; i++) {
    const item = departments[id][i]
    if (!departments[item.id]) {
      arr.push({
        name: item.name,
        key: item.id
      })
    } else {
      const new_arr = checkArr(departments, item.id)
      arr.push({
        name: item.name,
        key: item.id,
        children: new_arr
      })
    }
  }
  return arr
}

// 其他方法保持不变...
const onSelect = (selectedKeys, info) => {
  console.log('onSelect', selectedKeys, info)
  let nodes = []
  if (info) {
    nodes = info.selectedNodes
  }
  emit('update', selectedKeys, nodes)
  selectKeys.value = selectedKeys
}

const onExpandSingle = (expandedKeys, info) => {
  console.log('onExpand', expandedKeys, info)
  expandKeys.value = expandedKeys
}

const onExpand = (expandedKeys, info) => {
  console.log('onExpand', expandedKeys, info)
  if (checkKeys.value.includes(info.node.key)) {
    return
  }
  expandKeys.value = expandedKeys
}

const onCheck = (checkedKeys, info) => {
  console.log('onCheck', checkedKeys, info)
  let nodes = []
  if (info) {
    nodes = info.checkedNodes
  }
  const checkedKeyArray = checkedKeys.checked || checkedKeys
  emit('update', checkedKeyArray, nodes)
  checkKeys.value = checkedKeyArray
  
  if (info.checked && info.node.children) {
    expandKeys.value = expandKeys.value.filter(key => key !== info.node.key)
  }
}

const onChange = (e) => {
  console.log(`checked = ${e.target.checked}`)
  if (e.target.checked) {
    const topLevelParentKeyList = treeData.value.map(node => node.key)
    const topLevelParentNodes = [...treeData.value]
    
    if (props.type === 'single') {
      console.log('全选')
      selectKeys.value = []
      expandKeys.value = []
    } else {
      checkKeys.value = topLevelParentKeyList
      expandKeys.value = []
    }
    emit('update', topLevelParentKeyList, topLevelParentNodes)
  } else {
    selectKeys.value = []
    expandKeys.value = []
    checkKeys.value = []
    emit('update', [], [])
  }
}
</script>

<style scoped>
.tree-title-elli {
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>